package com.snl.micro.blog.comments.service.impl;

import com.snl.micro.blog.comments.client.UserClient;
import com.snl.micro.blog.comments.dao.respository.CommentRepository;
import com.snl.micro.blog.comments.pojo.po.CommentInfoPo;
import com.snl.micro.blog.comments.service.CommentService;
import com.snl.micro.blog.common.action.UserAction;
import com.snl.micro.blog.common.base.schuleThreadPool.CommonPool;
import com.snl.micro.blog.common.param.CommentSaveParam;
import com.snl.micro.blog.common.protocol.ResponseResult;
import com.snl.micro.blog.common.query.CommentQuery;
import com.snl.micro.blog.common.query.UserQuery;
import com.snl.micro.blog.common.vo.CommentVo;
import com.snl.micro.blog.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class CommentServiceImplement implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private UserClient userClient;

    @Override
    public List<CommentVo> query(CommentQuery query) {
        log.debug("你好,入参：{}",query);
        //调用后端请求
        UserQuery userQuery = new UserQuery();
        List<CommentVo> commentVos = new ArrayList<>();
        List<CommentInfoPo> pos = commentRepository.query(query);
        pos.forEach(po->{
            CommentVo commentVo = new CommentVo();
            //获取当前用户id
            Long userId = po.getUserId();
            userQuery.setId(userId);
            //获取用户业务响应数据
            ResponseResult<List<UserVo>> result =
                    userClient.query(userQuery);
            UserVo userVo = result.getData().get(0);
            BeanUtils.copyProperties(po,commentVo);
            commentVo.setUsername(userVo.getUsername());
            commentVos.add(commentVo);
        });
        return commentVos;
    }

    @Override
    public void save(CommentSaveParam param) {
        log.debug("业务层入参:{}",param);
        CommentInfoPo commentInfoPo = new CommentInfoPo();
        BeanUtils.copyProperties(param,commentInfoPo);
        commentInfoPo.setCreateTime(LocalDateTime.now());
        commentInfoPo.setUpdateTime(LocalDateTime.now());
        commentRepository.save(commentInfoPo);
        UserAction userAction = new UserAction();
        userAction.setUsername("xxxx");
        userAction.setCreateTime(LocalDateTime.now());
        userAction.setMessage("评论了");
        CommonPool.addAction(userAction);
    }
}
